import React from "react";
import { browserHistory } from "react-router";

class Nav extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            open: undefined
        };

        this.menuClick = this.menuClick.bind(this);
        this.getLocation = this.getLocation.bind(this);
        this.changeLocation = this.changeLocation.bind(this);
        this.getCurrent = this.getCurrent.bind(this);
    }

    menuClick(current, type){
        return () => {
            type == "item" ? this.setState({
                current,
                open: current
            }) : this.setState({
                current
            });
            this.changeLocation(current);
        }
    }

    getLocation(current = this.state.current) {
        const menus = this.props.menus || [];
        let nodes = [{ title: "车联网平台首页", url: "/dashboard" }];

        if(!current) {
            return nodes;
        }

        for(let i = 0, il = menus.length; i < il; i++){
            const menu = menus[i];
            if(menu.url == current.url) {
                nodes.push(menu);
                return nodes;
            }
            if(!menu.children || menu.children.length == 0) {
                continue;
            }
            for(let j = 0, jl = menu.children.length; j < jl; j++){
                const sub = menu.children[j];
                if(sub.url == current.url) {
                    nodes.push(menu);
                    nodes.push(sub);
                    return nodes;
                }
            }
        }

        return nodes;
    }

    changeLocation(current) {
        current && current.url && browserHistory.push(current.url);
    }

    getCurrent() {
        const links = this.props.pathName.split("/");
        const url = links[0] ? links[0] : links[1]
        return { url: `/${url}` };
    }

    render() {
        const menus = this.props.menus || [],
            { open } = this.state;
        const current = this.getCurrent();
        return <ul className="menu">
                   { menus.map((item, i) => <Menu key={ i } type="item" menu={ item } current={ current } open={ open } click={ this.menuClick } />) }
               </ul>
    }
}

class Menu extends React.Component {

    render() {
        const {menu, type, current, open, click} = this.props;

        return <li className={ type} data-active={ current && current.url == menu.url } data-open={ open && open.url == menu.url }>
                   <div className="title" onClick={ click(menu, type) } data-icon={menu.style}><span>{ menu.title }</span></div>
                   { type == "item" && menu.children && menu.children.length > 0
                     && <ul className="sub-menu">
                            { menu.children.map((item, i) => <Menu key={ i } type="sub-item" menu={ item } click={ click } />) }
                        </ul> }
               </li>
    }
}

export default Nav;